import { ElDropdown, ElDropdownItem, ElDropdownMenu, ElIcon } from 'element-plus';
import { ArrowDown } from '@element-plus/icons-vue';
import './index.scss';
import { PropType } from 'vue';
import { MciButton } from '../Button';
import { IOption } from '../Select';
import { newToString } from '@/utils/string';

export const MciDropdownItem = ElDropdownItem;
export const MciDropdownMenu = ElDropdownMenu;

export const MciDropdown = defineComponent({
  name: 'MciDropdown',
  props: {
    trigger: {
      type: String as PropType<'hover' | 'click' | 'contextmenu'>,
      default: 'hover'
    },
    text: {
      type: String,
      default: ''
    },
    linkIconGap: {
      type: Number,
      default: 8
    },
    type: {
      type: String as PropType<'default' | 'button'>,
      default: 'default'
    },
    list: {
      type: Array as PropType<IOption[]>,
      default: () => []
    }
  },
  emits: ['command'],
  setup(_, { emit }) {
    const dropdown = ref();

    return {
      onCommand: (command: string | number | object) => {
        emit('command', command);
      },
      dropdown
    };
  },
  render() {
    const { trigger, text, linkIconGap, type, $slots, onCommand } = this;

    const createDropdownDefault = () => {
      return (
        <>
          {text}
          <ElIcon class={`ml-${linkIconGap}`}>
            <ArrowDown />
          </ElIcon>
        </>
      );
    };

    const createDropdownList = () => {
      if (this.list.length) {
        return () => (
          <MciDropdownMenu>
            {this.list.map((item) => (
              <MciDropdownItem command={newToString(item.value)}>{item.label}</MciDropdownItem>
            ))}
          </MciDropdownMenu>
        );
      }
      return $slots.dropdown;
    };
    const slots = {
      ...$slots,
      dropdown: createDropdownList(),
      default:
        $slots.default ??
        (() => {
          if (type === 'button')
            return (
              <MciButton class="mci-dropdown-link flex items-center cursor-pointer">{createDropdownDefault()}</MciButton>
            );
          return (
            <span class="mci-dropdown-link flex items-center cursor-pointer text-value-14">
              {createDropdownDefault()}
            </span>
          );
        })
    };
    return <ElDropdown ref="dropdown" class="mci-dropdown" trigger={trigger} vSlots={slots} onCommand={onCommand} />;
  }
});
